import { hex_md5 } from './md5.js';
import { pathToBase64, base64ToPath } from './base64.js';
var COMMON_PUBLIC_TASK = null;
module.exports = {
	async com_select_file(v) {
		let _this = this;

		// #ifdef APP-PLUS
		const lemonjkFileSelect = uni.requireNativePlugin('lemonjk-FileSelect');

		_this.store_set_state({ state_name: 'WORKING_SELECT_FILE', state_value: true });
		return new Promise((resolve, reject) => {
			lemonjkFileSelect.showPicker(
				{
					//各属性配置见下方【showPicker可配置参数说明】
					pathScope: '/Download',
					mimeType: 'audio/mpeg',
					utisType: 'public.mp3',
					loadingToast: 'no',
					filterConfig: {
						//对象里配置的属性要同时满足
						// fileName:['base.apk','config.txt','配置文件.yaml'],  //属性数组满足其中一项
						// fileSize:String(1*1024*1024),  //byte 单位：字节
						fileExtension: ['mp3'], //属性数组满足其中一项
					},
				},
				async result => {
					console.log(result);
					_this.store_set_state({ state_name: 'WORKING_SELECT_FILE', state_value: false });
					if (result.code == '0') {
						let path = _this.objJudge(result.files) ? result.files[0].filePath : false;
						resolve(path);
					} else {
						resolve(false);
					}

					// if (result.code == 1001) {
					// 	uni.showModal({
					// 		title: '需要文件访问权限',
					// 		content: '您还未授权本应用读取文件。为保证您可以正常上传文件，请在权限设置页面打开文件访问权限（不同手机厂商表述可能略有差异）请根据自己手机品牌设置',
					// 		confirmText: '去授权',
					// 		cancelText: '算了',
					// 		success(e) {
					// 			if (e.confirm) {
					// 				// 跳转到应用设置页
					// 				// lemonjkFileSelect.gotoSetting();
					// 			}
					// 		},
					// 	});
					// }
				}
			);
		});
		// #endif
	},
	com_init_data(res) {
		let _this = this;

		for (const key in res) {
			let element = res[key];
			let _type = _this.gettype(element);
			// console.log(_type, res[key], key);
			switch (_type) {
				case null:
					res[key] = '--';
					break;
				case undefined:
					res[key] = '--';
					break;
				// case String:
				// 	if (!_this.objJudge(res[key])) {
				// 		res[key] = '--';
				// 		console.log(_type, res[key], key);
				// 		debugger;
				// 	}
				// 	break;
			}
		}
		return res;
	},
	// 加载初始化事件
	// 0 最后结束初始化页面
	// 1 开始显示加载中
	// 2 接口处理根据 state成功与否返回 成功提示或者返回错误信息msg
	com_loading_fun(config = {}) {
		let _this = this;
		let {
			mode = 1,
			k = 'nextreq',
			title = '加载中...',
			hide_time = 300,
			judge_var = 'repeat_once',
			repeat_loding = false,
			suc_callback = false,
			fail_callback = false,
			suc_icon = 'success',
			fail_icon = 'none',
			show_fail_msg = true,
			response = false,
		} = config;
		let END_TITLE = title;
		if (mode == 0) {
			// 结束加载数据loading
			_this.change_var['timeout_loading'] = false;
			_this.com_loading({
				status: 0,
				k,
				hide_time: 200,
				time: 0,
				throttle: true,
				callback() {
					typeof _this.render_req == 'undefined' ? false : (_this.render_req = true);
					_this.pulldownJudge();
					suc_callback && suc_callback();
					_this.get_view_info({
						viewNmae: '#page_main_id',
						viewCallBack(_info) {
							if (_this.objJudge(_info) && _this.objJudge(_info.height)) {
								_this.change_var['page_height'] = _this.pxTorpx(_info.height);
							}
						},
					});
				},
			});
		} else if (mode == 1) {
			if (repeat_loding) {
				// 重复显示加载
				_this.com_loading({ status: 1, k, title, mask: true, throttle: false });
				_this.change_var['timeout_loading'] = true;
			} else {
				// 只提示一次
				if (_this.change_var[judge_var]) {
					_this.change_var[judge_var] = false;
					_this.change_var['timeout_loading'] = true;
					_this.com_loading({ status: 1, k, title, mask: true, throttle: false });
				}
			}
			setTimeout(() => {
				if (_this.change_var['timeout_loading']) {
					_this.com_loading_fun({ mode: 0, throttle: true });
				}
			}, _this.timeout);
		} else if (mode == 2) {
			let { state, msg = '网络请求错误', data } = response;
			let END_ICON = 'none';
			let END_CALLBACK = false;
			if (state == 1) {
				END_CALLBACK = suc_callback(response);
				END_ICON = suc_icon;
			} else {
				END_CALLBACK = fail_callback;
				END_ICON = fail_icon;
				if (show_fail_msg) {
					END_TITLE = msg;
				} else {
					END_TITLE = false;
				}
			}
			_this.com_loading({ status: 2, k, title: END_TITLE, throttle: true, icon: END_ICON, hide_time, callback: END_CALLBACK });
		}
	},
	// 卸载页面时需要停止播放音频
	com_page_destory(d) {
		let play_context = typeof d;
		// console.log(play_context);
		if (play_context == 'undefined') {
		} else {
			d.pause();
			d.destroy();
		}
	},
	// 获取缓存
	get_cache() {
		let k = uni.getStorageInfoSync().currentSize;
		// let t = uni.getStorageInfoSync();
		// console.log(t)

		let txt = '';
		if (k <= 1024) {
			txt = '';
			// } else if (k < 1024) {
			//     txt = k + "B";
		} else if (k < 1048576) {
			txt = (k / 1024).toFixed(2) + 'KB';
		} else if (k < 1073741824) {
			txt = (k / 1048576).toFixed(2) + 'MB';
		} else {
			txt = (k / 1073741824).toFixed(2) + 'GB';
		}
		return txt;
	},
	// 清除缓存
	async clear_cache(item) {
		let _this = this;
		let f = await this.com_modal({
			content: '确认清除缓存？',
		});
		if (!f) return;
		if (!_this.com_loading({ status: 1, title: '清除中...' })) return;
		let t = uni.getStorageInfoSync();
		// console.log(JSON.stringify(t.keys), t.keys)
		let filter_key = ['base_customer_phone', 'usertoken', 'userid', 'userinfo'];

		t.keys.reduce((p, n) => {
			// console.log(p, n, p.indexOf(n), 't.keys')
			if (p.indexOf(n) == -1) {
				uni.removeStorageSync(n);
			}
			return p;
		}, filter_key);

		setTimeout(() => {
			_this.com_loading({ status: 2, title: '清除成功' });
			_this.judge_view(item);
		}, 1000);
	},

	init_map_scale(range, type) {
		/*
       
       1 -> 13
       3 -> 12
       5 -> 11
       10 -> 10
type = select
        */
		let _this = this;
		if (type == 'select') {
			if (range <= 1) return 14;
			else if (range <= 3) return 13;
			else if (range <= 6) return 12;
			else if (range <= 10) return 11;
		} else {
			if (range <= 1) return 13;
			else if (range <= 3) return 12;
			else if (range <= 5) return 11;
			else if (range <= 10) return 10;
		}
	},

	init_map(o, type = 'list') {
		let _this = this;
		let v = _this.deepclone(o);

		//  v.fence_range 半径公里数 如1km -> 1
		let radius = v.fence_range * 1000;

		let color = 'rgba(31,209,194,0.31)';
		let fillColor = 'rgba(31,209,194,0.31)';
		if (type == 'list') {
		} else {
			color = '#1fd1c24f';
			fillColor = '#1fd1c24f';
		}
		let circles = [
			{
				latitude: parseFloat(v.fence_lat),
				longitude: parseFloat(v.fence_lng),
				color,
				fillColor,
				radius,
				strokeWidth: 0,
			},
		];
		_this.$set(v, 'circles', circles);

		let _range = v.fence_range;
		let _scale = 0;

		// if (type == 'select') {
		//     _this.$set(v, 'scale', 12)
		// } else {
		//     _scale = _this.init_map_scale(_range)
		//     _this.$set(v, 'scale', _scale)
		// }
		_scale = _this.init_map_scale(_range, type);
		_this.$set(v, 'scale', _scale);
		return v;
	},

	getindex(e) {
		let _this = this;
		let i = -1;
		let { key = 'id', value, list = 'page_list' } = e;
		for (let index = 0; index < _this[list].length; index++) {
			const element = _this[list][index];
			if (element[key] == value) {
				i = index;
				break;
			}
		}
		return i;
	},

	swiperchange(e) {
		// console.log('开始切换');
		this.$set(this.swiper_dots, e.target.id, e.detail.current);
		// can_set_newindex =  e.detail.current;
		// this.swiper_dots[`${e.target.id}`] = e.detail.current;
		// this.$forceUpdate();
	},

	// 计算公里数
	get_distance(e) {
		let { p_lat, p_lng, n_lat, n_lng } = e;

		let EARTH_RADIUS = 6378.137; // 地球半径
		let radLat1 = (p_lat * Math.PI) / 180.0; //p_lat * Math.PI / 180.0=>弧度计算
		let radLat2 = (n_lat * Math.PI) / 180.0;
		let a = radLat1 - radLat2;
		let b = (p_lng * Math.PI) / 180.0 - (n_lng * Math.PI) / 180.0;
		let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10; // 输出为米
		// return {
		//     m: s * 1000,
		//     km: Number(s.toFixed(2))
		// }

		// console.log(e, 'get_distance', s * 1000)
		// console.log(e, 'get_distance', Number(s.toFixed(2)))

		return s;
	},
	// 计算速度
	get_speed(d, time) {
		let _s = time;
		if (d == 0 || _s == 0) {
			return 0;
		} else {
			return (d / _s) * 60 * 60;
		}
	},

	async pathToBase64_fun(path) {
		return await pathToBase64(path);
	},
	// base64 加密和解密
	async base64_en(v) {
		return await this.pathToBase64_fun(v);
	},
	// base64_de(v) {
	//     return base64ToPath(v)
	// },
	// 加密
	data_handle(v) {
		// console.log(JSON.stringify(v), v, '_this.data_handle(v)')
		// MeEnybtPM%#PEDYGnCuEzhkjmzc2S@NG 前后端规定的密钥
		// v 传递过来的数据结构 进行json转义后再md5加密
		let d = {
			jsonstr: JSON.stringify(v),
			token: hex_md5('MeEnybtPM%#PEDYGnCuEzhkjmzc2S@NG' + JSON.stringify(v)),
		};
		// console.log(JSON.stringify(d), d.token, 'd.token')
		return d;
	},
	// 百度地图坐标转换腾讯地图
	bMapToQQMap(lng, lat) {
		if (lng == null || lng == '' || lat == null || lat == '') return [lng, lat];

		var x_pi = (3.14159265358979324 * 3000.0) / 180.0;
		var x = parseFloat(lng) - 0.0065;
		var y = parseFloat(lat) - 0.006;
		var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
		var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
		var lng = (z * Math.cos(theta)).toFixed(12) * 1;
		var lat = (z * Math.sin(theta)).toFixed(12) * 1;
		return [lng, lat];
	},

	// 换腾讯地图坐标转百度地图
	qqMapToBMap(lng, lat) {
		if (lng == null || lng == '' || lat == null || lat == '') return [lng, lat];

		var x_pi = (3.14159265358979324 * 3000.0) / 180.0;
		var x = parseFloat(lng);
		var y = parseFloat(lat);
		var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
		var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
		var lng = (z * Math.cos(theta) + 0.0065).toFixed(12);
		var lat = (z * Math.sin(theta) + 0.006).toFixed(12);
		return [lng, lat];
	},

	// 查看密码强度
	getLvl(pwd) {
		let lvl = 0; //默认是0级
		//密码中是否有数字,或者是字母,或者是特殊符号
		if (/[0-9]/.test(pwd)) {
			lvl++;
		}
		//判断密码中有没有字母
		if (/[a-zA-Z]/.test(pwd)) {
			lvl++;
		}
		//判断密码中有没有特殊符号
		if (/[^0-9a-zA-Z_]/.test(pwd)) {
			lvl++;
		}
		return lvl; //1 3
	},

	callphone(e) {
		let phone = e;

		if (Object.prototype.toString.call(phone).slice(8, -1) == 'Number') {
			phone = phone.toString();
		}
		uni.makePhoneCall({
			phoneNumber: phone,
		});
	},
	// 跳转客服
	customer_wechat() {
		let _this = this;
		uni.share({
			provider: 'weixin',
			openCustomerServiceChat: true,
			customerUrl: 'https://work.weixin.qq.com/kfid/kfcd1ccda887b892d83', //企业微信地址
			corpid: 'wwbffeed0d77f3a4ac', //企业id
			success: res => {
				// console.log('success:234' + JSON.stringify(res));
			},
			fail: err => {
				// console.log('fail:3' + JSON.stringify(err));
			},
		});
	},

	copydata(data) {
		let _this = this;
		if (!_this.objJudge(data)) return;
		uni.setClipboardData({
			data,
			success: res => {
				_this.com_msg('复制成功');
			},
			fail: res => {},
		});
	},

	//校验tonken
	async getusertoken() {
		let _this = this;
		let usertoken = uni.getStorageSync('usertoken');
		let { state } = await _this.com_getdata({
			url: '/login/token',
			data_handle_on: false,
			method: 'GET',
			data: {
				token: usertoken,
			},
		});
		if (state == 1) {
			let user_res = await _this.com_getdata({
				url: '/user/info',
				id_name: 'user_id',
			});
			if (user_res.state == 1) {
				_this.set_user(user_res);
			}
			return true;
		} else if (state == -2) {
			_this.clear_user('-2');
			return false;
		} else {
			return false;
		}
	},

	check_update() {
		let _this = this;
		// #ifdef MP-WEIXIN
		const updateManager = wx.getUpdateManager(); //1. 检查小程序是否有新版本发布
		updateManager.onCheckForUpdate(function (res) {
			// console.log(res);
			// 请求完新版本信息的回调
			if (res.hasUpdate) {
				//2. 小程序有新版本，则静默下载新版本，做好更新准备
				updateManager.onUpdateReady(function () {
					wx.showModal({
						title: '更新检测',
						content: '检测到新版本，即将重启小程序？',
						showCancel: false,
						success: function (res) {
							if (res.confirm) {
								//3. 新的版本已经下载好，调用applyUpdate应用新版本并重启
								updateManager.applyUpdate();
							} else if (res.cancel) {
								//不应用
							}
						},
					});
				});
			}
		});
		// #endif
	},

	set_user(v, type = 'check') {
		let _this = this;
		let target = '';
		if (type == 'login') {
			uni.setStorageSync('usertoken', v.token || v.data);
			target = v.info || v.model;
		} else {
			// 检查token并且更新用户信息
			target = v.data || v.info;
		}

		if (_this.objJudge(target)) {
			uni.setStorageSync('userid', target.id);
			if (_this.objJudge(target.user_openid)) {
				uni.setStorageSync('openid', target.user_openid);
			}
			let is_normal_user = false;
			if (target.user_status == 0) {
				is_normal_user = true;
			}
			uni.setStorageSync('is_normal_user', is_normal_user);

			_this.store_set_state_config({ state_name: 'USER_MSG', data: target });
			_this.store_set_state({ state_name: 'USER_LOGIN', state_value: true });
		}
	},

	loginJudge() {
		let usertoken = uni.getStorageSync('usertoken');
		if (!usertoken) {
			return -1;
		} else {
			return 1;
		}
	},

	com_padding_fun(_arr) {
		let _this = this;
		let _n = _arr.length;
		let _back = _arr;
		let target = _this.COMMON_VAR.safeAreaInsets_bot;
		if (target > 0) {
			switch (_n) {
				case 1:
					_back = [_arr[0], _arr[0], target];
					break;
				case 2:
					_back = [_arr[0], _arr[1], target];
					break;
				case 3:
					_back = [_arr[0], _arr[1], target];
					break;
				case 4:
					_back = [_arr[0], _arr[1], target, _arr[2]];
					break;
			}
		}
		return _back;
	},

	padding_judge_safe(_arr) {
		let _this = this;
		let _n = _arr.length;
		let _back = _arr;
		let target = _this.COMMON_VAR.safeAreaInsets_bot;
		if (target > 0) {
			let _bot = 0;
			switch (_n) {
				case 1:
					_bot = _arr[0] > target ? _arr[0] : target;
					_back = [_arr[0], _arr[0], _bot];
					break;
				case 2:
					_bot = _arr[0] > target ? _arr[0] : target;
					_back = [_arr[0], _arr[1], _bot];
					break;
				case 3:
					_bot = _arr[2] > target ? _arr[2] : target;
					_back = [_arr[0], _arr[1], _bot];
					break;
				case 4:
					_bot = _arr[2] > target ? _arr[2] : target;
					_back = [_arr[0], _arr[1], _bot, _arr[3]];
					break;
			}
		}
		let padding = '';
		if (_back.length > 0) {
			_back.forEach(v => {
				padding += padding ? ` ${v}rpx` : `${v}rpx`;
			});
		}
		return padding;
	},

	set_pagetop(vv) {
		let _this = this;
		_this.page_render = false;
		_this.change_var.page_top = vv;
		_this.page_render = true;
		_this.module_judge_render();

		_this.change_var.page_content_top = _this.change_var.page_top + _this.change_var.page_nav;
	},
	set_pagebot(vv) {
		let _this = this;
		_this.change_var.page_bot = vv;
		_this.module_judge_render();
	},
	set_pagetab(vv) {
		let _this = this;
		if (this.objJudge(vv)) {
			_this.change_var.page_nav = vv;
			_this.change_var.page_content_top = _this.change_var.page_top + _this.change_var.page_nav;
		}
	},
	// 主动登录
	async zhudon_login(url, modal = true) {
		let _this = this;
		if (_this.loginJudge() == -1) {
			if (modal) {
				let _flag = await _this.com_modal({ title: `提示`, content: '您当前状态尚未登录', confirmText: '马上登录' });
				if (_flag) {
					if (_this.$refs.pagelogin) {
						if (url) {
							uni.setStorageSync('login_to_url', url);
						}
						_this.$refs.pagelogin.page_login();
					}
				} else {
					return false;
				}
			} else {
				if (_this.$refs.pagelogin) {
					if (url) {
						uni.setStorageSync('login_to_url', url);
					}
					_this.$refs.pagelogin.page_login();
				}
			}

			return false;
		} else {
			_this.goweburl_f(url);
			return true;
		}
	},

	check_pic_all(newurl) {
		// , oss_style = "?x-oss-process=style/750_auto"
		// let _this = this;
		// if (!newurl) {
		//     return '';
		// } else if (newurl.length < 4) {
		//     return newurl
		// } else if ((newurl.substring(0, 4) == "http" || newurl.substring(0, 1) == "/") && newurl.indexOf(_this
		//         .oss_url) == -1 && newurl.indexOf('?x-oss-process=') == -1) {

		//     return newurl;
		// } else {
		//     let url = newurl.substr(newurl.length - 3);
		//     if (url == 'gif' || url == 'GIF') {
		//         oss_style = '';
		//     }
		//     let r = '';
		//     if (newurl.indexOf(_this.oss_url) == -1) {
		//         r = _this.oss_url + newurl;
		//         // debugger
		//     } else {
		//         r = newurl;
		//     }
		//     if (newurl.indexOf('?x-oss-process=') == -1) {
		//         r += (oss_style != -1 ? oss_style : '');
		//     } else {
		//         r = newurl;
		//     }
		//     return r
		// }

		return newurl;
	},

	async logout_fun(callback = 'refresh') {
		let _this = this;
		let f = await this.com_modal({
			// title: '',
			content: '确认退出登录？',
		});
		if (f) {
			_this.clear_user(callback);
		}
	},
	//过滤手机号码 s 开始位置 n 星星个数
	changePhone(value, s = 3, n = 4) {
		if (value) {
			let len = value.length;
			let x = value.substring(s + n);
			let k = value.substring(0, s);
			let star = new Array(n).fill('*').join('');
			let values = k + star + x;
			return values;
		} else {
			return '';
		}
	},

	get_address_detail(v, type = 'detail') {
		if (type == 'detail') {
			return `${v.province}${v.city}${v.district}${v.street}`;
		}
	},

	back_setting() {
		return new Promise((r, j) => {
			uni.getSetting({
				success(res) {
					r(res.authSetting);
				},
			});
		});
	},
	ceil_number(num, tt = 10) {
		// 将数字向上取整
		let roundedNum = Math.ceil(num);
		// 如果数字的个位不为 0，则将数字加上差值以确保个位为 0
		if (roundedNum % tt !== 0) {
			roundedNum += tt - (roundedNum % tt);
		}
		return roundedNum;
	},

	// 取规则校验数据
	com_test_check(value, key) {
		let _this = this;
		let _config = _this.COMMON_VAR.page_check_config[key];
		let regular = _config.regular;

		if (_this.objJudge(regular)) {
			return _this[regular].test(value);
		}
	},
	// 批量校验
	com_page_check(o) {
		let _this = this;
		let { keys_config, form } = o;
		let pass = true;
		for (let index = 0; index < keys_config.length; index++) {
			let { check_key, null_tips, error_tips = false, check_fun = false } = keys_config[index];
			if (!error_tips) {
				error_tips = null_tips;
			}
			if (!form[check_key]) {
				// 空提示
				_this.com_msg(null_tips);
				pass = false;
				break;
			}
			if (check_fun) {
				let _c = check_fun(form[check_key]);
				if (_c) {
				} else {
					_this.com_msg(error_tips);
					pass = false;
					break;
				}
			}
		}
		return pass;
	},

	// 经纬度地址解析
	com_getaddress(v) {
		let _this = this;
		let _config = this.com_set_config();
		let { latitude, longitude } = v;
		let data = {
			key: _config.map_key,
			location: `${longitude},${latitude}`,
		};
		return new Promise((resolve, reject) => {
			_this.com_getdata({
				url: 'https://restapi.amap.com/v3/geocode/regeo',
				data_handle_on: false,
				mode: 'network',
				method: 'GET',
				data,
				data_fun(data) {
					if (data.status == 1) {
						resolve(data.regeocode);
					} else {
						resolve({
							formatted_address: '未知地址',
							addressComponent: false,
						});
					}
				},
			});
		});
	},

	getCenterLonLat(point1, point2) {
		let { latitude: oneLat, longitude: oneLon } = point1;
		let { latitude: twoLat, longitude: twoLon } = point2;
		// oneLon, oneLat, twoLon, twoLat
		//oneLon：第一个点的经度；oneLat：第一个点的纬度；twoLon：第二个点的经度；twoLat：第二个点的纬度；
		let aLon = 0,
			aLat = 0;
		let bLon = Number(oneLon) - Number(twoLon);
		let bLat = Number(oneLat) - Number(twoLat);
		//Math.abs()绝对值
		if (bLon > 0) {
			aLon = Number(oneLon) - Math.abs(bLon) / 2;
		} else {
			aLon = Number(twoLon) - Math.abs(bLon) / 2;
		}
		if (bLat > 0) {
			aLat = Number(oneLat) - Math.abs(bLat) / 2;
		} else {
			aLat = Number(twoLat) - Math.abs(bLat) / 2;
		}
		return {
			latitude: aLat,
			longitude: aLon,
		};
	},
};
